package com.everflourish.yeah100.utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.everflourish.yeah100.ui.ExitPopup;
import com.yalantis.ucrop.UCrop;

import java.io.File;

/**
 * 作者：Created by liqisi on 2016/7/15.
 * 时间：2016/7/15
 */
public class ImageSelectHolder {

    private static final String TAG = "MainActivity";
    public static final String IMAGE_HEADER = "image_header";
    public static final String IMAGE_QUESTION = "image_question";
    private static final String SAMPLE_CROPPED_IMAGE_NAME = "SampleCropImage.jpg";
    public static boolean isDisable = true;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION2 = 102;
    // 相册
    public static final int REQUEST_SELECT_PICTURE = 0x01;
    // 照相机
    public static final int CAMERA_WITH_DATA = 0x111;
    // 拍摄的临时文件
    public static File mTempFile = new File(
            Environment.getExternalStorageDirectory(), "temp_shoot.jpg");
    private Activity mActivity;
    private ExitPopup exitPopup = null;

    public ImageSelectHolder(Activity activity) {
        mActivity = activity;
    }

    /**
     * 弹出上传图片选择
     */
    public void open(View v, String upLoadType) {
        exitPopup = new ExitPopup(mActivity, "题目上传");
        if (upLoadType.equals(IMAGE_HEADER)) {
            exitPopup.setMsg("头像上传");
        } else if (upLoadType.equals(IMAGE_QUESTION)){
            exitPopup.setMsg("题目上传");
        }
        exitPopup.setCameraListener(new ExitPopup.OnClickListener() {
            @Override
            public void onClick(ExitPopup exitPopup) {
                // 相机拍摄
                camera();
                exitPopup.dismiss();
            }
        });
        exitPopup.setAlbumListener(new ExitPopup.OnClickListener() {
            @Override
            public void onClick(ExitPopup exitPopup) {
                // 手机相册
                album();
                exitPopup.dismiss();
            }
        });
        exitPopup.show((View) v.getParent(), mActivity);
    }

    /**
     * 相机拍摄
     */
    public void camera() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
            Toast.makeText(mActivity, "没有找到SD卡或者正在使用请关闭usb连接模式",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                    && ActivityCompat.checkSelfPermission(mActivity, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(mActivity,
                        new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_READ_ACCESS_PERMISSION);
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
            mActivity.startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (Exception e) {
            Toast.makeText(mActivity, "没有找到相机", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 手机相册
     */
    public void album() {
        if (!hasSdcard()) {// 判断是否有SD卡
            Toast.makeText(mActivity, "没有找到SD卡或者正在使用请关闭usb连接模式",
                    Toast.LENGTH_SHORT);
            return;
        }
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                    && ActivityCompat.checkSelfPermission(mActivity, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(mActivity,
                        new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_READ_ACCESS_PERMISSION);
            }
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    "image/*");
            mActivity.startActivityForResult(intent, REQUEST_SELECT_PICTURE);
        } catch (Exception e) {
            Toast.makeText(mActivity, "没有找到相册", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public void startCropActivity(@NonNull Uri uri) {
        String destinationFileName = SAMPLE_CROPPED_IMAGE_NAME;
        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(mActivity.getCacheDir(), destinationFileName)));
        uCrop = basisConfig(uCrop);
        uCrop = advancedConfig(uCrop);
        uCrop.start(mActivity);
    }

    private UCrop basisConfig(UCrop uCrop) {
        uCrop = uCrop.useSourceImageAspectRatio();
        return uCrop;
    }

    private UCrop advancedConfig(@NonNull UCrop uCrop) {
        UCrop.Options options = new UCrop.Options();
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        options.setCompressionQuality(90);
        options.setHideBottomControls(false);
        options.setFreeStyleCropEnabled(true);
        return uCrop.withOptions(options);
    }

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    public void handleCropError(@NonNull Intent result) {
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            Log.e(TAG, "handleCropError: ", cropError);
            Toast.makeText(mActivity, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(mActivity, "Unexpected error", Toast.LENGTH_SHORT).show();
        }
    }

}